package com.hackordie.commons.hardware.components;

import java.util.ArrayList;
import java.util.List;

import com.hackordie.commons.software.AProgram;
import com.hackordie.constants.EComponentsType;
import com.hackordie.constants.ESoftwareType;

public class RamMemory extends AComponent {

    private int totalCapacity;
    private int usedCapacity;
    private List<AProgram> programs = new ArrayList<AProgram>();

    public RamMemory(String componentName, int energyToTurOn, int totalCapacity) {
        super(componentName, EComponentsType.RamMemory, energyToTurOn);

        this.totalCapacity = totalCapacity;
        this.usedCapacity = 0;
    }

    // getters
    public int getTotalCapacity() {
        return totalCapacity;
    }

    public int getUsedCapacity() {
        return usedCapacity;
    }

    public int getAvailableCapacity() {
        return totalCapacity - usedCapacity;
    }
        
    public AProgram getProgramByName(String name) {
        for (int i = 0; i < programs.size(); i++) {
            if (programs.get(i).getName().equals(name)) {
                return programs.get(i);
            }
        }
        return null;
    }

    public List<AProgram> getFilesByType(ESoftwareType type) {
        List<AProgram> filesToReturn = new ArrayList<AProgram>();

        for (int i = 0; i < programs.size(); i++) {
            if (programs.get(i).getSoftwareType().equals(type)) {
                filesToReturn.add(programs.get(i));
            }
        }

        return filesToReturn;
    }

    // programs

    public boolean setPrograms(AProgram file) {
        if (!started) {
            return false;
        }

        if (file.getSize() <= (totalCapacity - usedCapacity)) {
            programs.add(file);
            usedCapacity += file.getRequiredRam();
            return true;
        }
        return false;
    }

    public boolean deleteProgram(String name) { //TODO AGREGAR FINALS!
        if (started) {
            for (int i = 0; i < programs.size(); i++) {
                if (programs.get(i).getName().equals(name)) {
                    usedCapacity -= programs.get(i).getRequiredRam();
                    programs.remove(i);
                    return true;
                }
            }
        }
        return false;
    }
}
